package com.qf.service.serviceImpl;

import com.qf.pojo.BaseResp;
import com.qf.service.Myemail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class MyemailImpl implements Myemail {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public BaseResp cun(String email) {
        BaseResp baseResp = new BaseResp();
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;
        try{
            mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setSubject("注册验证码");

            Random random = new Random();
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0;i<4;i++){
                stringBuffer.append(random.nextInt(10));
            }
            mimeMessageHelper.setText("<font style='color:red'>注册验证码为：</font>"+stringBuffer.toString(),true);
            javaMailSender.send(mimeMessage);
            redisTemplate.opsForValue().set(email,stringBuffer.toString(),300, TimeUnit.SECONDS);
            baseResp.setCode(200);
            baseResp.setMgs("邮件发送成功");

        }catch (Exception e){
            e.printStackTrace();
            baseResp.setCode(203);
            baseResp.setMgs("邮件发送失败");
        }

        return baseResp;

    }

    @Override
    public Boolean qu(String email, String code) {

        String o = (String)redisTemplate.opsForValue().get(email);

        if (o!=null & o.equals(code)){
            return true;
        }
        return false;
    }
}
